/*
 * PennTreeScanner.java
 *
 * Created on July 12, 2006, 12:20 PM
 *
 */

package galronnlp.io;

import galronnlp.util.Symbol;
import galronnlp.util.SymbolGenerator;
import java.util.Scanner;
import java.util.regex.*;

/**
 *
 * @author Daniel A. Galron
 */
public class PennTreeScanner {
    
    private Scanner scanner;
    private SymbolGenerator gen;
    private String lastFound = null;
    private String wholeString = "";
    
    private final Pattern START       = Pattern.compile("\\(\\s*\\(");
    private final Pattern CONSTITUENT = Pattern.compile("\\(\\S+");
    private final Pattern LEAF        = Pattern.compile("\\(\\S+\\s*\\S+\\)");
    private final Pattern SYMBOL      = Pattern.compile("\\S+");
    
    
    public PennTreeScanner(String string, SymbolGenerator g) {
        this.wholeString = string;
        this.gen = g;
    }
    
    public boolean hasNextStart() {
        Matcher m = START.matcher(this.wholeString);
        return m.lookingAt();
    }
    
    public boolean hasNextConstituent() {
        Matcher m = CONSTITUENT.matcher(this.wholeString);
        return m.lookingAt();
    }
    
    public boolean hasNextLeaf() {
        Matcher m = LEAF.matcher(this.wholeString);
        return m.lookingAt();
    }
    
    public boolean hasNextSymbol() {
        Matcher m = SYMBOL.matcher(this.wholeString);
        return m.lookingAt();
    }
    
    public String nextStart() {
        return this.wholeString;
    }
    
    public String nextConstituent() {
        int numParen = 0;
        int i = 0;
        for(i = 0; i < this.wholeString.length(); i++) {
            if(this.wholeString.charAt(i) == '(')
                numParen++;
            else if(this.wholeString.charAt(i) == ')')
                numParen--;
            if(numParen == 0)
                break;
        }
        String ret = this.wholeString.substring(0, i+1).trim();
        this.wholeString = this.wholeString.substring(i+1).trim();
        return ret;
    }
    
    public String nextLeaf() {
        int end = this.wholeString.indexOf(')');
        String ret = this.wholeString.substring(0, end + 1).trim();
        this.wholeString = this.wholeString.substring(end + 1).trim();
        return ret;
    }
    
    public Symbol nextSymbol() {
        int end = this.wholeString.indexOf(' ');
        String ret;
        if(end != -1) {
            ret = this.wholeString.substring(0, end).trim();
            this.wholeString = this.wholeString.substring(end).trim();
        }
        else {
            ret = this.wholeString;
            this.wholeString = "";
        }
        return gen.create(ret);
    }
}
